# Author: Tylor Zhang
# Email: zhangyunqiao@gmail.com

try:
  from cStringIO import StringIO
except ImportError:
  from StringIO import StringIO

from PIL import Image
from django.core.mail import send_mail
import thread
from Queue import Queue

def get_thumbnail(data, size):
  if hasattr(data, 'temporary_file_path'):
    file = data.temporary_file_path()
  else:
    if hasattr(data, 'read'):
      file = StringIO(data.read())
    else:
      file = StringIO(data['content'])
  image = Image.open(file)
  image.thumbnail(size)
  return image

def thread_func(queue):
  print 'Starting thread...'
  while True:
    func, params = queue.get(block=True) 
    print 'Child thread running function...'
    apply(func, params)
  print 'End thread...'

# Thread pool class
class ThreadPool(object):
  def __init__(self, threads=1):
    self.queue = Queue()
    for i in range(threads):
      thread.start_new_thread(thread_func, (self.queue,))
  
  def apply_async(self, func, param_tuple):
    self.queue.put((func, param_tuple), block=True)
    
# Start 5 processes to send email
email_pool = ThreadPool(threads=5)

# send email asynchronously. Any failure will be ignored.
# This function will call django.core.mail.send_email(subject, message, from_email, recipient_list)
def async_send_mail(subject, message, from_email, recipient_list):
  result = email_pool.apply_async(send_mail, 
      (subject, message, from_email, recipient_list, True))
